package com.kky.pp.activity.register

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.Manifest
import android.net.Uri
import android.text.TextUtils
import androidx.core.view.isVisible
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.kky.pp.dot.AFDotLogUtil
import com.kky.pp.dot.DotLogEventName
import com.kky.pp.dot.DotLogUtil
import com.kky.pp.common.Constant
import io.rong.imkit.SpName
import com.kky.pp.adapter.AddPhotoSelectAdapter
import com.kky.pp.base.TitleBasePresenterImpl
import com.kky.pp.entity.IMTokenGetEntity
import com.kky.pp.entity.UserProfileEntity
import com.kky.pp.rongyun.RongConfigUtil
import com.custom.base.config.BaseConfig
import com.custom.base.entity.OkHttpBodyEntity
import com.custom.base.http.OkHttpFromBoy
import com.custom.base.http.OkHttpManager
import com.custom.base.http.SDOkHttpResoutCallBack
import com.custom.base.util.IntentUtil
import com.kky.pp.bean.UserPhotoBean
import com.kky.pp.activity.location.RequestLocationActivity
import com.kky.pp.activity.login.helper.LoginRegisterHelper
import com.kky.pp.util.CollectionUtils
import com.kky.pp.util.DateUtils
import com.kky.pp.util.PermissionUtils
import com.kky.pp.util.UploadPhoto
import com.kky.pp.view.Loading.LoadingDialog
import com.kky.pp.view.upImage.UpImageView
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.PictureConfig
import com.luck.picture.lib.entity.LocalMedia
import io.rong.imkit.RongIM
import io.rong.imlib.model.UserInfo
import java.util.*
import java.util.stream.Collectors

class RegisterPresenter : TitleBasePresenterImpl<RegisterContact.View>(),
    RegisterContact.Presenter {
    private lateinit var photoSelectAdapter: AddPhotoSelectAdapter
    private var photoSelectPosition: Int = 0 //选择照片
    private var gender = -1 // 0未选择 1男2女0未知
    private var imagesShow = arrayListOf(
        UserPhotoBean("", "", "",false),
        UserPhotoBean("", "", "",false),
        UserPhotoBean("", "", "",false),
        UserPhotoBean("", "", "",false),
        UserPhotoBean("", "", "",false),
        UserPhotoBean("", "", "",false)
    )

    val loginRegisterHelper by lazy { LoginRegisterHelper() }

    override fun initBundle(bundle: Bundle) {
        mView?.apply {
            initNickName()
            viewUpImageView.setData(imagesShow)

            txtLookingNext.setOnClickListener {
                actionLoading.isVisible = true
                actionLoading.playAnimation()
                val requestParamsMap = hashMapOf<String, Any>()
                requestParamsMap["birthday"] = DateUtils.replace(txtDate.text.toString())
                val imagesShow = viewUpImageView.userImages

                if (CollectionUtils.isNotEmpty(imagesShow)) {
                    val list = arrayListOf<String>()
                    repeat(imagesShow.size) {
                        if (imagesShow[it].imageUrl != "") {
                            list.add(imagesShow[it].imageUrl)
                        }
                    }
                    requestParamsMap["images"] = list
                    requestParamsMap["avatarUrl"] = imagesShow[0].imageUrl
                }
                requestParamsMap["nickName"] = editNickname.text.toString().trim()
                requestParamsMap["gender"] = getGender()
                requestParamsMap["userWant"] =
                    (mActivity as RegisterActivity).iwantAdapter?.getSingleSelect()?.code ?: -1

                val addProfileActivity = mActivity as RegisterActivity
                if (getGender() != 0) {
                    val bodyList = arrayListOf<Long>()
                    val bodyShapeList =
                        if (getGender() == 1) addProfileActivity.manAdapter?.dataList else addProfileActivity.womanAdapter?.dataList
                    val selectShape = bodyShapeList?.stream()?.filter { it.selected == 1 }
                        ?.collect(Collectors.toList())
                    selectShape?.stream()?.forEach {
                        bodyList.add(it.code)
                    }
                    requestParamsMap["bodyShape"] = bodyList
                }

                val youAccepts = (mActivity as RegisterActivity).youAccpetAdapter?.getSelect()
                val list = arrayListOf<Long>()
                youAccepts?.stream()?.forEach {
                    list.add(it.code)
                }
                requestParamsMap["youAccept"] = list
                requestParamsMap["lookingFor"] =
                    if (getGender() == 1) 2 else if (getGender() == 2) 1 else 0

                OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                    override fun addBody(requestBody: OkHttpBodyEntity) {
                        requestBody.setPost(Constant.user_user_info_init_url)
                        requestParamsMap.forEach { (key, value) ->
                            requestBody.add(key, value)
                        }
                    }
                }, object : SDOkHttpResoutCallBack<UserProfileEntity>() {
                    override fun onSuccess(entity: UserProfileEntity) {
                        AFDotLogUtil().addRegisterEvent(mActivity)
                        if (CollectionUtils.isNotEmpty(entity.data.images)) {
                            repeat(entity.data.images.size) {
                                Glide.with(mActivity)
                                    .load(entity.data.images[it])
                                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                                    .preload()
                            }
                        }
                        BaseConfig.getInstance.setBoolean(SpName.profileComplete, true)
                        BaseConfig.getInstance.setString(
                            SpName.nickName,
                            editNickname.text.toString()
                        )
                        entity.data.avatarUrl?.apply {
                            BaseConfig.getInstance.setString(
                                SpName.avatarUrl,
                                this
                            )
                        }
                        if (PermissionUtils.lacksPermission(
                                mActivity,
                                Manifest.permission.ACCESS_FINE_LOCATION
                            ) && PermissionUtils.lacksPermission(
                                mActivity,
                                Manifest.permission.ACCESS_COARSE_LOCATION
                            )
                        ) {
                            if (entity.data.nickName != null) {
                                RongIM.getInstance().refreshUserInfoCache(
                                    UserInfo(
                                        entity.data.userCode,
                                        entity.data.nickName,
                                        Uri.parse(entity.data.avatarUrl)
                                    )
                                )
                            }
                            IntentUtil.startActivity(RequestLocationActivity::class.java)
                            finish()
                        } else {
                            OkHttpManager.instance.requestInterface(object : OkHttpFromBoy {
                                override fun addBody(requestBody: OkHttpBodyEntity) {
                                    requestBody.setPost(Constant.im_token_Url)
                                }
                            }, object : SDOkHttpResoutCallBack<IMTokenGetEntity>() {
                                override fun onSuccess(parms: IMTokenGetEntity) {
                                    RongConfigUtil.connectIMLogin(
                                        parms.data.token,
                                        entity.data.userCode,
                                        entity.data.nickName,
                                        entity.data.avatarUrl ?: ""
                                    )
                                }

                                override fun onFailure(code: Int, msg: String) {
                                }
                            })
                        }
                    }

                    override fun onFinish() {
                        super.onFinish()
                        actionLoading.cancelAnimation()
                        actionLoading.isVisible=false
                    }

                    override fun onFailure(code: Int, msg: String) {
                        showToast(msg)
                    }
                })
//                HttpRequest.commonNotify(608, "")
                DotLogUtil.setEventName(DotLogEventName.USER_PROFILE_WYH_ON_NEXT_CLICK).commit()
            }
        }
        super<TitleBasePresenterImpl>.initBundle(bundle)
    }

    fun deleteImage(viewUpImageViews:UpImageView) {
        val viewUpImageView = viewUpImageViews
        val userPhotoBeans = viewUpImageView.userImages
        val position = viewUpImageView.photoSelectPosition
        userPhotoBeans.removeAt(position)
        viewUpImageView.setData(userPhotoBeans)
    }


    override fun onBackClick() {
        (mActivity as RegisterActivity).onBackListener()
    }

    fun setGender(gender: Int) {
        this.gender = gender
    }

    fun getGender(): Int {
        return gender
    }

    /**
     * 昵称输入
     */
    private fun initNickName() {
        mView?.apply {
            editNickname.addTextChangedListener(object : TextWatcher {
                override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

                }

                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                    txtNicknameNext.isEnabled = editNickname.text.toString().isNotEmpty()
                    txtNicknameNext.alpha =
                        if (editNickname.text.toString().isNotEmpty()) 1f else 0.5f
                    if (s?.length != null) {
                        tvNameExceedHint.isVisible = s.length >= 30
                    }
                }

                override fun afterTextChanged(p0: Editable?) {
                }

            })
        }
    }

    private fun addImage(selectPosition: Int, selectList: ArrayList<LocalMedia>?) {
        mView?.apply {
            selectList?.forEach {
                val path = when {
                    it.isCompressed -> {
                        it.compressPath
                    }

                    it.isCut -> {
                        it.cutPath
                    }

                    else -> {
                        it.realPath
                    }
                }
                if (path.contains(".mp4", true) || it.mimeType.contains(
                        ".3gp",
                        true
                    ) || it.mimeType.contains(".mov", true)
                ) {
                    showToast("pls upload photo.")
                    return
                }
                val userPhotoBeans = viewUpImageView.userImages
                val userPhotoBean = userPhotoBeans[selectPosition]
                val opType = if (TextUtils.isEmpty(userPhotoBean.imageUrl)) 1 else 2
                val imageCode = if (opType == 1) "" else {
                    userPhotoBean.imageCode
                }

                LoadingDialog.showLoading(mActivity, "upload...")
                UploadPhoto.uploadFileNewPhoto(
                    mActivity,
                    path,
                    imageCode,
                    object : UploadPhoto.OnLister {
                        override fun onSuccess(successPath: String, imageCode: String) {
                            txtPhotoNext.isEnabled = true

//                        val userImages = mActivity.viewUpImageView.userImages
//                        val selectPosition = (mActivity as ProfileInfoActivity).nowSelectImagePosition
//                        userImages?.removeAt(selectPosition)
//                        userImages?.add(selectPosition,successPath)
//                        userImages?.let { it1 -> mActivity.viewUpImageView.setData(it1) }
                            val opType = if (TextUtils.isEmpty(imageCode)) 1 else 2
                            if (opType == 2) {
                                var selectPosition = 0
                                for (i in 0 until userPhotoBeans.size) {
                                    if (userPhotoBeans[i].imageCode == imageCode) {
                                        selectPosition = i
                                        break
                                    }
                                }
                                savePhoto(
                                    imageCode,
                                    successPath,
                                    path,
                                    opType,viewUpImageView
                                )
                            } else {
                                var lastPosition = 0
                                for (i in 0 until userPhotoBeans.size) {
                                    if (userPhotoBeans[i].imageUrl == "") {
                                        lastPosition = i
                                        break
                                    }
                                }
                                savePhoto(
                                    "",
                                    successPath,
                                    path,
                                    opType,viewUpImageView
                                )
                            }

                            LoadingDialog.dismissLoading()

                        }

                        override fun fail() {
                            var lastPosition = 0
                            LoadingDialog.dismissLoading()
                            showToast("upload error,pls try again")
                        }

                    })
            }
        }
    }

    fun savePhoto(
        imageCode: String,
        imageUrl: String,
        path: String,
        opType: Int,
        viewUpImageViews:UpImageView
    ) {
        val viewUpImageView =viewUpImageViews
        val userPhotoBeans = viewUpImageView.userImages
        if (opType == 1) {
            var lastPosition = 0
            for (i in 0 until userPhotoBeans.size) {
                if (userPhotoBeans[i].imageUrl == "") {
                    lastPosition = i
                    break
                }
            }
            userPhotoBeans[lastPosition].imageUrl = imageUrl
            userPhotoBeans[lastPosition].imageLoadUrl = path
            userPhotoBeans[lastPosition].imageCode = imageCode
            userPhotoBeans[lastPosition].loading = false
            viewUpImageView.userImages = userPhotoBeans
            viewUpImageView.upDataItemImage(lastPosition)
        } else if (opType == 2) {
            var lastPosition = 0
            for (i in 0 until userPhotoBeans.size) {
                if (userPhotoBeans[i].imageCode == imageCode) {
                    lastPosition = i
                    break
                }
            }
            userPhotoBeans[lastPosition].imageUrl = imageUrl
            userPhotoBeans[lastPosition].imageLoadUrl = path
            userPhotoBeans[lastPosition].imageCode = imageCode
            userPhotoBeans[lastPosition].loading = false
            viewUpImageView.userImages = userPhotoBeans
            viewUpImageView.upDataItemImage(lastPosition)
        } else if (opType == 3) {
            val position = viewUpImageView.photoSelectPosition
            userPhotoBeans.removeAt(position)
            viewUpImageView.setData(userPhotoBeans)
        }
    }

    fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                PictureConfig.CHOOSE_REQUEST -> {
                    val selectList = PictureSelector.obtainSelectorList(data)
                    addImage(photoSelectPosition, selectList)
                }
            }
        }
    }
}